<?php

namespace app\http\controller\admin\chat;

use app\model\ChatAppModel;
use app\model\ChatMessageModel;
use app\model\ChatMessageRelationModel;
use app\http\controller\admin\Controller;

class HistoryController extends Controller
{
    /**
     * 通信记录
     *
     * @param ChatMessageRelationModel $model
     * @return void
     */
    public function index(ChatMessageRelationModel $model)
    {
        if ($this->request->isAjax()) {
            $query = $this->request->get();
            $data = $model->getList($query);
            return $this->success('ok', $data['list'], ['count' => $data['total']]);
        }

        $apps = [];
        $showApp = $this->request->get('app') ? false : true;
        if ($showApp) {
            $apps = ChatAppModel::instance()->field(['id', 'title'])->select();
            array_unshift($apps, ['id' => '', 'title' => '']);
        }
        $showWaiter = $this->request->get('waiter_id') ? false : true;

        return $this->fetch('chat/history/index', [
            'app' => $apps,
            'showApp' => $showApp,
            'showWaiter' => $showWaiter
        ]);
    }

    /**
     * 通信记录
     *
     * @param ChatMessageModel $message
     * @param ChatMessageRelationModel $messageRelation
     * @return void
     */
    public function info(ChatMessageModel $message, ChatMessageRelationModel $messageRelation)
    {
        $idx = $this->request->get('idx', 0);
        $info = $messageRelation->where(['id' => $idx])->get();
        if ($info->isEmpty()) {
            return $this->error('query faild');
        }
        $data = $message->getMessage($idx);

        return $this->fetch('chat/history/content', [
            'info'  => $info->toArray(),
            'list'  => json_encode($data, JSON_UNESCAPED_UNICODE)
        ]);
    }
}
